﻿
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Apps.IBLL;
using Apps.Common;
using Apps.Models;
using Apps.Models.Sys;

using System.Text;
using Apps.Web.Core;
using Apps.Locale;
using Apps.IBLL.Sys;
using Apps.Web.Model;

namespace Apps.Web.Controllers
{
    public class SysStructController : BaseController
    {
        [Dependency]
        public ISysStructBLL m_BLL { get; set; }
        ValidationErrors errors = new ValidationErrors();


        [SupportFilter]
        public ActionResult Index()
        {

            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList(string id)
        {
            if (id == null)
                id = "0";
            List<SysStructModel> list = m_BLL.GetList(id);
            var json = from r in list
                       select new SysStructModel()
                       {
                           Id = r.Id,
                           Name = r.Name,
                           ParentId = r.ParentId,
                           Sort = r.Sort,
                           Enable = r.Enable,
                           Higher = r.Higher,
                           Remark = r.Remark,
                           CreateTime = r.CreateTime,
                           state = (m_BLL.GetList(r.Id).Count > 0) ? "closed" : "open"
                       };


            return Json(json);
        }

        [HttpPost]
        public JsonResult GetListByComTree(string id)
        {
            List<SysStructModel> list = m_BLL.GetList(id);
            var json = from r in list
                       select new SysTreeModel()
                       {
                           id = r.Id,
                           text = r.Name,
                           state = (m_BLL.GetList(r.Id).Count > 0) ? "closed" : "open"
                       };


            return Json(json);
        }

        [HttpPost]
        public JsonResult GetListByParentId(string id)
        {
            if (id == null)
                id = "0";
            List<SysStructModel> list = m_BLL.GetList(id);
            StringBuilder sb = new StringBuilder("");
            foreach (var i in list)
            {
                sb.AppendFormat("<option value='{0}'>{1}</option>", i.Id, i.Name);
            }

            return Json(sb.ToString());
        }

        #region 创建
        [SupportFilter]
        public ActionResult Create(string id)
        {
            SysStructModel tempObj = m_BLL.GetById(id);
            string structname = string.Empty;
            if (tempObj != null)
                structname = tempObj.Name;

            SysStructModel entity = new SysStructModel()
            {
                ParentId = id,
                ParentName = structname,
                Enable = true
            };
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(SysStructModel model)
        {
            model.Id = ResultHelper.NewId;
            model.CreateTime = ResultHelper.NowTime;
            if (model != null && ModelState.IsValid)
            {

                if (m_BLL.Create(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "创建", "SysStruct");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "创建", "SysStruct");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        [HttpPost]
        [SupportFilter(ActionName = "Edit")]
        public JsonResult ChangeState(string Id)
        {

            if (!string.IsNullOrWhiteSpace(Id))
            {
                SysStructModel mode = m_BLL.GetById(Id);
                if (mode != null)
                {
                    mode.Enable = !mode.Enable;
                    if (m_BLL.Edit(ref errors, mode))
                    {
                        LogHandler.WriteServiceLog(GetUserId(), "ENABLED" + mode.Id, "成功", "修改状态", "SysStruct");
                        return Json(JsonHandler.CreateMessage(1, "状态修改成功！"));
                    }
                    else
                    {
                        string ErrorCol = errors.Error;
                        LogHandler.WriteServiceLog(GetUserId(), "ENABLED" + mode.Id + "," + ErrorCol, "失败", "修改状态", "SysStruct");
                        return Json(JsonHandler.CreateMessage(0, "状态修改失败！" + ErrorCol));
                    }

                }
                else
                {
                    return Json(JsonHandler.CreateMessage(0, "更改状态失败，传入主键为空"));
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, "更改状态失败，传入主键为空"));
            }
        }
        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            string struName = string.Empty;
            SysStructModel entity = m_BLL.GetById(id);
            SysStructModel tempObj = m_BLL.GetById(entity.ParentId);
            struName = tempObj == null ? "" : tempObj.Name;
            entity.ParentName = struName;
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(SysStructModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(model.ParentId))
                    model.ParentId = "0";
                if (m_BLL.Edit(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "修改", "SysStruct");
                    return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "修改", "SysStruct");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ":" + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细

        public ActionResult Details(string id)
        {
            //获取父级
            List<SysStructModel> list = m_BLL.GetList("0");

            foreach (var model in list)
            {
                model.clildren = m_BLL.GetList(model.Id);
                foreach (var m in model.clildren)
                {
                    m.clildren = m_BLL.GetList(m.Id);
                }
            }

            return View(list);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public JsonResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (m_BLL.Delete(ref errors, id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + id, "成功", "删除", "SysStruct");
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + id + "," + ErrorCol, "失败", "删除", "SysStruct");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }


        }
        #endregion

        public ActionResult _StructParentSelect(string ControlID,string ControlName,string SelectValue="",string CurrentID="")
        {
            ViewBag.ControlID = ControlID;
            ViewBag.ControlName = ControlName;
            ViewBag.SelectValue = SelectValue;

            var list = m_BLL.GetList(ref GridPager.NotPage, "");

            List<selectmodel> result = new List<selectmodel>();
            AppendChildSelect("", CurrentID, "0", list, ref result);

            return View(result);
        }

        private void AppendChildSelect(string preFixedStr,string CurrentID,string ParentID,List<SysStructModel> list,ref List<selectmodel> result)
        {
            var childlist = (from u in list where u.ParentId == ParentID orderby u.Sort ascending select u).ToList();

            if(childlist!=null && childlist.Count>0)
            {
                foreach(var child in childlist)
                {
                    if(child.Id!= CurrentID)
                    {
                        selectmodel item = new selectmodel();
                        item.name = string.Format("{0}{1}", preFixedStr, child.Name);
                        item.value = child.Id;

                        result.Add(item);

                        AppendChildSelect(preFixedStr + "--", CurrentID, child.Id, list, ref result);
                    }
                }
            }
        }
    }
}
